const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const {auth} = require('../middleware/auth');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadPath = path.join(__dirname, '../../img');

    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'work_' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  fileFilter: function (req, file, cb) {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'), false);
    }
  },
  limits: {
    fileSize: 5 * 1024 * 1024 
  }
});

async function getWriterIdByName(writerName) {
  const [rows] = await pool.execute(
    'SELECT id FROM writer WHERE name = ?',
    [writerName]
  );
  return rows.length > 0 ? rows[0].id : null;
}

router.get('/all', async (req, res) => {
  try {
    const [rows] = await pool.execute(
      'SELECT id, title, writer_id, is_biography, detail_url, cover_path, created_at FROM work ORDER BY created_at DESC'
    );
    res.json(rows);
  } catch (error) {
    console.error('获取所有作品列表失败:', error);
    res.status(500).json({
      message: '获取所有作品列表失败',
      error: error.message
    });
  }
});

router.get('/writer/:writerId', async (req, res) => {
  try {
    const writerId = parseInt(req.params.writerId, 10);
    const page = parseInt(req.query.page, 10) || 1;
    const pageSize = parseInt(req.query.pageSize, 10) || 10;
    const isBiography = req.query.is_biography;

    let query = 'SELECT id, title, is_biography, detail_url, cover_path, created_at FROM work WHERE 1=1';
    let countQuery = 'SELECT COUNT(*) as count FROM work WHERE 1=1';
    const queryParams = [];
    const countParams = [];

    if (!isNaN(writerId)) {
      query += ' AND writer_id = ?';
      countQuery += ' AND writer_id = ?';
      queryParams.push(writerId);
      countParams.push(writerId);
    }

    if (isBiography !== undefined) {
      const isBiographyInt = parseInt(isBiography, 10) === 1 ? 1 : 0;
      query += ' AND is_biography = ?';
      countQuery += ' AND is_biography = ?';
      queryParams.push(isBiographyInt);
      countParams.push(isBiographyInt);
    }

    query += ` ORDER BY created_at DESC LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}`;
    console.log('执行 countQuery:', countQuery, countParams);
    console.log('执行 query:', query, queryParams);
    const [countRows] = await pool.execute(countQuery, countParams);
    const total = countRows[0].count;
    const [rows] = await pool.execute(query, queryParams);

    res.json({
      total,
      works: rows
    });

  } catch (error) {
    console.error('获取作品列表失败:', error);
    res.status(500).json({
      message: '获取作品列表失败',
      error: error.message
    });
  }
});


router.get('/:id', async (req, res) => {
  try {
    const workId = req.params.id;
    
    const [rows] = await pool.execute(
      'SELECT id, title, writer_id, is_biography, detail_url, cover_path, created_at FROM work WHERE id = ?',
      [workId]
    );

    if (rows.length === 0) {
      return res.status(404).json({ message: '作品不存在' });
    }

    res.json(rows[0]);
  } catch (error) {
    console.error('获取作品详情失败:', error);
    res.status(500).json({
      message: '获取作品详情失败',
      error: error.message
    });
  }
});

router.post('/', auth, upload.single('cover'), async (req, res) => {
  try {
    const { title, writer_id, writer_name, is_biography, detail_link } = req.body;

    if (!title) {
      return res.status(400).json({ message: '作品标题不能为空' });
    }

    let actualWriterId = writer_id;
    if (!actualWriterId && writer_name) {
      actualWriterId = await getWriterIdByName(writer_name);
      if (!actualWriterId) {
        return res.status(400).json({ message: '作家不存在' });
      }
    }

    if (!actualWriterId) {
      return res.status(400).json({ message: '作家ID或作家名称不能为空' });
    }

    const [writers] = await pool.execute('SELECT id FROM writer WHERE id = ?', [actualWriterId]);
    if (writers.length === 0) {
      return res.status(400).json({ message: '作家不存在' });
    }

    let coverPath = null;
    if (req.file) {
      coverPath = `/img/${req.file.filename}`;
    }

    const isBiographyInt = parseInt(is_biography) === 1 ? 1 : 0;

    const [result] = await pool.execute(
      'INSERT INTO work (title, writer_id, is_biography, detail_url, cover_path) VALUES (?, ?, ?, ?, ?)',
      [title, actualWriterId, isBiographyInt, detail_link || null, coverPath]
    );

    const workId = result.insertId;
    const [rows] = await pool.execute(
      'SELECT id, title, writer_id, is_biography, detail_url, cover_path, created_at FROM work WHERE id = ?',
      [workId]
    );

    res.status(201).json(rows[0]);
  } catch (error) {
    console.error('创建作品失败:', error);
    res.status(500).json({
      message: '创建作品失败',
      error: error.message
    });
  }
});

router.put('/:id', auth, upload.single('cover'), async (req, res) => {
  try {
    const workId = req.params.id;
    const { title, is_biography, detail_link } = req.body;

    if (!title) {
      return res.status(400).json({ message: '作品标题不能为空' });
    }

    const [existingWorks] = await pool.execute(
      'SELECT id, cover_path FROM work WHERE id = ?',
      [workId]
    );

    if (existingWorks.length === 0) {
      return res.status(404).json({ message: '作品不存在' });
    }

    let coverPath = existingWorks[0].cover_path;
    if (req.file) {
      if (existingWorks[0].cover_path) {
        const oldImagePath = path.join(__dirname, '../..', existingWorks[0].cover_path);
        if (fs.existsSync(oldImagePath)) {
          fs.unlinkSync(oldImagePath);
        }
      }
      coverPath = `/img/${req.file.filename}`;
    }

    const isBiographyInt = parseInt(is_biography) === 1 ? 1 : 0;

    await pool.execute(
      'UPDATE work SET title = ?, is_biography = ?, detail_url = ?, cover_path = ? WHERE id = ?',
      [title, isBiographyInt, detail_link || null, coverPath, workId]
    );


    const [rows] = await pool.execute(
      'SELECT id, title, writer_id, is_biography, detail_url, cover_path, created_at FROM work WHERE id = ?',
      [workId]
    );

    res.json(rows[0]);
  } catch (error) {
    console.error('更新作品失败:', error);
    res.status(500).json({
      message: '更新作品失败',
      error: error.message
    });
  }
});

router.delete('/:id', auth, async (req, res) => {
  try {
    const workId = req.params.id;

    const [existingWorks] = await pool.execute(
      'SELECT id, cover_path FROM work WHERE id = ?',
      [workId]
    );

    if (existingWorks.length === 0) {
      return res.status(404).json({ message: '作品不存在' });
    }

    // 删除封面图片
    if (existingWorks[0].cover_path) {
      const imagePath = path.join(__dirname, '../..', existingWorks[0].cover_path);
      if (fs.existsSync(imagePath)) {
        fs.unlinkSync(imagePath);
      }
    }

    await pool.execute('DELETE FROM work WHERE id = ?', [workId]);

    res.json({ message: '作品删除成功' });
  } catch (error) {
    console.error('删除作品失败:', error);
    res.status(500).json({
      message: '删除作品失败',
      error: error.message
    });
  }
});

module.exports = router; 